package com.zengyu.toiusuapplication.api;

import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zengyu.toiusuapplication.Interceptor.AuthInterceptor;

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//创建一个 Retrofit 客户端来初始化 API 服务
//单例模式实现，防止多次创建-实例化，ApiClient.init()
public class ApiClient {
    public static String base_ImageUrl = "http://192.168.191.90:8080";
    private static final String BASE_URL = base_ImageUrl + "/api/";
    private static Retrofit retrofit;
    private static Context appContext;

    private ApiClient() {
    }

    public static void init(Context context) {
        appContext = context.getApplicationContext();
    }

    public static ApiService getApiService() {
        if (appContext == null) {
            throw new IllegalStateException("ApiClient 未初始化，请先在 LoginActivity 中调用 ApiClient.init(context)");
        }

        if (retrofit == null) {
            synchronized (ApiClient.class) {
                if (retrofit == null) {
                    // 初始化 Retrofit
                    OkHttpClient client = new OkHttpClient.Builder()
                            .addInterceptor(new AuthInterceptor(appContext))
                            .connectTimeout(60, TimeUnit.SECONDS)
                            .readTimeout(60, TimeUnit.SECONDS)
                            .writeTimeout(60, TimeUnit.SECONDS)
                            .build();

                    Gson gson = new GsonBuilder()
                            .setLenient()
                            .create();

                    retrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .client(client)
                            .addConverterFactory(GsonConverterFactory.create(gson))
                            .build();
                }
            }
        }
        return retrofit.create(ApiService.class);
    }
}

